package com.ndbg.demo.utils;


import org.apache.poi.util.IOUtils;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 下载模板通用工具类
 *
 * @author xzk
 * @date 2022/12/2
 */
public class ExcelImportUtil {

    /**
     * 导入模板存放路径
     */
    private static final String RESOURCE_PATH = "classpath:";

    public static void downloadImportTemplate(HttpServletResponse response, String path) {
        OutputStream out = null;
        InputStream inputStream = null;
        InputStream fis = null;
        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            inputStream = resolver.getResource(RESOURCE_PATH + path).getInputStream();
            fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            IOUtils.readFully(fis, buffer);
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("111", StandardCharsets.UTF_8.name()) + ".xlsx");
            response.setContentType("application/octet-stream");
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(buffer);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException("xxx");
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(inputStream);
        }
    }
}
